//
//  PhoneVerifyViewController.m
//  HelpThePoor
//
//  Created by 韩中睿 on 2017/7/21.
//  Copyright © 2017年 van7ish. All rights reserved.
//

#import "PhoneVerifyViewController.h"

@interface PhoneVerifyViewController ()

/** <#注释#> */
@property (nonatomic, strong) UIImageView * headerImageView;
/** <#注释#> */
@property (nonatomic, strong) UIButton * backButton;

/** <#注释#> */
@property (nonatomic, strong) UIButton * confirmButton;

/** <#注释#> */
@property (nonatomic, strong) UIView * registWayPhone;

/** <#注释#> */
@property (nonatomic, strong) UIImageView * phoneImageView;
/** <#注释#> */
@property (nonatomic, strong) UITextField * phoneTextField;
/** <#注释#> */
@property (nonatomic, strong) UIImageView * idCodeImageView;
/** <#注释#> */
@property (nonatomic, strong) UITextField * idCodeTextField;
/** <#注释#> */
@property (nonatomic, strong) UIButton * idCodeButton;
/** 倒计时timer */
@property (nonatomic, strong) NSTimer * timer;
/** <#name#> */
@property (nonatomic, assign) NSInteger seconds;
/** <#注释#> */
@property (nonatomic, strong) UIView * overView;

@end

@implementation PhoneVerifyViewController

- (UIView *)overView{
    if (!_overView) {
        _overView = [[UIView alloc] initWithFrame:CGRectMake(0, self.headerImageView.bottom, SCREEN_W, HeightScale(200))];
        _overView.backgroundColor = COLOR_LIGHTBGCOLOR;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(32)) / 2, HeightScale(100), WidthScale(32), WidthScale(32))];
        imageView.image = ImageNamed(@"Done-1");
        [_overView addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, imageView.bottom + HeightScale(20), SCREEN_W, HeightScale(30))];
        label.font = FONTSIZE(17);
        label.textColor = COLOR_GREEN;
        label.textAlignment = NSTextAlignmentCenter;
        label.text = @"已完成实名认证!";
        [_overView addSubview:label];
        _overView.hidden = YES;
    }
    return _overView;
}

- (UIView *)registWayPhone{
    if (!_registWayPhone) {
        _registWayPhone = [[UIView alloc] initWithFrame:CGRectMake(0, self.headerImageView.bottom + HeightScale(20), SCREEN_W, HeightScale(100))];
        
        
        _phoneImageView = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(40), HeightScale(20), WidthScale(11.5), HeightScale(18))];
        _phoneImageView.image = ImageNamed(@"number");
        [_registWayPhone addSubview:_phoneImageView];
        
        
        
        _phoneTextField = [[UITextField alloc] initWithFrame:CGRectMake(CGRectGetMaxX(self.phoneImageView.frame) + WidthScale(15), HeightScale(10), SCREEN_W - WidthScale(180), HeightScale(40))];
        _phoneTextField.placeholder = @"输入手机号";
        _phoneTextField.font = FONTSIZE(17);
        
        UIImageView *underLine = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(20), _phoneTextField.bottom - 0.5, SCREEN_W - WidthScale(40), 0.5)];
        underLine.image = ImageNamed(@"fengexian");
        _phoneTextField.keyboardType = UIKeyboardTypeNumberPad;
        _phoneTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_registWayPhone addSubview:_phoneTextField];
        [_registWayPhone addSubview:underLine];
        
        
        
        
        _idCodeImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.phoneImageView.frame.origin.x, CGRectGetMaxY(self.phoneTextField.frame) + HeightScale(20), WidthScale(14), HeightScale(16))];
        _idCodeImageView.image = ImageNamed(@"yanzhengma");
        [_registWayPhone addSubview:_idCodeImageView];
        
        
        
        _idCodeTextField = [[UITextField alloc] initWithFrame:CGRectMake(self.phoneTextField.frame.origin.x, CGRectGetMaxY(self.phoneTextField.frame) + HeightScale(10), self.phoneTextField.frame.size.width, self.phoneTextField.frame.size.height)];
        _idCodeTextField.placeholder = @"输入验证码";
        _idCodeTextField.font = FONTSIZE(17);
        _idCodeTextField.keyboardType = UIKeyboardTypeNumberPad;
        UIImageView *underLine1 = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(20), _idCodeTextField.bottom - 0.5, SCREEN_W - WidthScale(40), 0.5)];
        underLine1.image = ImageNamed(@"fengexian");
        _idCodeTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
        [_registWayPhone addSubview:self.idCodeTextField];
        [_registWayPhone addSubview:underLine1];
        
        
        
        _idCodeButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - WidthScale(120), self.idCodeTextField.frame.origin.y, WidthScale(100), HeightScale(40))];
        [_idCodeButton setTitle:@"获取" forState:UIControlStateNormal];
        _idCodeButton.titleLabel.font = FONTSIZE(17);
        [_idCodeButton setTitleColor:COLOR_GREEN forState:UIControlStateNormal];
        
        [_idCodeButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
        __weak typeof(self) weakSelf = self;
        [_idCodeButton initWithBlock:^(UIButton * idCodeButton) {
            
            if (idCodeButton.enabled) {
                DLog(@"获取验证码");
                [weakSelf requestIDCode];
                
            }
        } for:UIControlEventTouchUpInside];
        
        [_registWayPhone addSubview:_idCodeButton];
        
    }
    return _registWayPhone;
}


- (UIButton *)confirmButton{
    if (!_confirmButton) {
        _confirmButton = [[UIButton alloc] initWithFrame:CGRectMake((SCREEN_W - WidthScale(80)) / 2, self.view.height - HeightScale(60), WidthScale(80), HeightScale(40))];
        [_confirmButton setTitle:@"确定" forState: UIControlStateNormal];
        [_confirmButton setTitleColor:COLOR_GREEN forState:UIControlStateNormal];
        _confirmButton.titleLabel.font = [UIFont boldSystemFontOfSize:WidthScale(17)];
        
        __weak typeof(self)weakSelf = self;
        [_confirmButton initWithBlock:^(id obj) {
            DLog(@"确定");
            
            if (self.overView.hidden) {
                [weakSelf requestVerification];
            } else {
                [self dismissViewControllerAnimated:YES completion:nil];
            }

            
            
            
        } for:UIControlEventTouchUpInside];
    }
    return _confirmButton;
}

- (UIButton *)backButton{
    if (!_backButton) {
        _backButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
        [_backButton setImage:ImageNamed(@"back") forState:UIControlStateNormal];
        _backButton.transform = CGAffineTransformMakeRotation(-M_PI_2);
        __weak typeof(self)weakSelf = self;
        [_backButton initWithBlock:^(id obj) {
            DLog(@"返回");
            [weakSelf dismissViewControllerAnimated:YES completion:nil];
        } for:UIControlEventTouchUpInside];
    }
    return _backButton;
}

- (UIImageView *)headerImageView{
    if (!_headerImageView) {
        _headerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_W / 2)];
        _headerImageView.image = ImageNamed(@"background");
        _headerImageView.userInteractionEnabled = YES;
    }
    return _headerImageView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    
    [self.view addSubview:self.headerImageView];
    
    [self.view addSubview:self.backButton];
    
    [self.view addSubview:self.registWayPhone];
    
    [self.view addSubview:self.confirmButton];
    
    [self.view addSubview:self.overView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    if (_timer) {
        [_timer invalidate];
        _timer = nil;
    }
    
}

/** NSTimer selector */
- (void)timerCountdown:(NSTimer *)timer{
    if (self.seconds) {
        [self.idCodeButton setTitle:[NSString stringWithFormat:@"已发送(%lds)", (long)self.seconds] forState:UIControlStateDisabled];
        self.seconds -= 1;
        DLog(@"倒计时 %ld", self.seconds);
    } else {
        [self.idCodeButton setTitle:[NSString stringWithFormat:@"已发送"] forState:UIControlStateDisabled];
        self.idCodeButton.enabled = YES;
        [self.timer invalidate];
        self.timer = nil;
        
    }
    
}

/** 获取短信验证码 */
- (void)requestIDCode{
    if ([Tool isMobileNumber:self.phoneTextField.text]) {
        
        NSDictionary *parameters = @{@"userCode": self.phoneTextField.text};
        NSString *URL = [NSString stringWithFormat:KIDCodeURL, KHostAddress, self.phoneTextField.text];
        [ZRRequestManager POST:URL parameters:parameters success:^(id responseObject) {
            DLog(@"%@", responseObject);
            if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
                [ZRProgressHUD showMsgWithoutView:@"验证码已发送到您的手机"];
                
                self.seconds = 60;
                self.idCodeButton.enabled = NO;
                self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerCountdown:) userInfo:nil repeats:YES];
                
                [_idCodeButton setTitle:@"已发送" forState:UIControlStateDisabled];
                [_idCodeButton setTitleColor:COLOR_FONTLIGHTGRAY forState:UIControlStateDisabled];
            } else {
                [ZRProgressHUD showMsgWithoutView:[responseObject objectForKey:@"data"]];
            }
        } failure:^(NSError *error) {
            DLog(@"获取验证码失败");
        }];
    } else {
        [ZRProgressHUD showMsgWithoutView:@"请输入正确的手机号码"];
    }
}

- (void)requestVerification{
    NSString *url = [NSString stringWithFormat:KidentityVerify, KHostAddress, [AppDelegate shareDelegate].userModel.userId, _phoneTextField.text, _idCodeTextField.text, @""];
    [ZRRequestManager POST:url parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] intValue] == 0) {
            
            self.overView.hidden = NO;
            
            NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
            
            NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:userData]];
            [tempDic addEntriesFromDictionary:@{@"mobileNumber":self.phoneTextField.text}];
            [AppDelegate shareDelegate].userModel = [UserModel modelWithDictionary:tempDic];
            
            //字典序列化并存储到NSUserDefaults
            userData = [NSKeyedArchiver archivedDataWithRootObject:tempDic];
            
            [[NSUserDefaults standardUserDefaults] setObject:userData forKey:@"user"];

            
        } else {
            
        }
        
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];
}

@end
